using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class HorizontalCardHolder : MonoBehaviour
{
    [SerializeField] private Card selectedCard;
    [SerializeField] private Card hoveredCard;
    [SerializeField] private GameObject slotPrefab;
    
    [SerializeField] private int cardsToSpawn = 7;
    private RectTransform rect;

    public List<Card> CardsList = new List<Card>();
    bool isCrossing = false;


    public List<GameObject> CardSlots = new List<GameObject>();
    public RectTransform CardHolder;
    // Start is called before the first frame update
    void Start()
    {
        GenerateCards();
    }

    public void GenerateCards()
    {
        for (int i = 0; i < CardSlots.Count; i++)
        {
            Destroy(CardSlots[i]);
        }
        CardSlots.Clear();
        isCrossing = false;
        CardsList?.Clear();
        selectedCard = null;
        hoveredCard = null;
        for (int i = 0; i < cardsToSpawn; i++)
        {
            var go = Instantiate(slotPrefab, transform);
            CardSlots.Add(go);
            var card = go.GetComponentInChildren<Card>();
            CardsList?.Add(card);
            card.Init(CardHolder);
        }
        
        //CardsList = GetComponentsInChildren<Card>().ToList();
        rect = GetComponent<RectTransform>();

        int cardCount = 0;

        foreach (Card card in CardsList)
        {
            card.PointerEnterAction += CardPointerEnter;
            card.PointerExitAction += CardPointerExit;
            card.BeginDragAction += BeginDrag;
            card.EndDragAction += EndDrag;
            card.name = cardCount.ToString();
            card.CardName.text = cardCount.ToString();
            cardCount++;
        }
        CustomYieldInstruction f = new WaitForSecondsRealtime(.1f);

        StartCoroutine(Frame());

        IEnumerator Frame()
        {
            yield return f;
            for (int i = 0; i < CardsList.Count; i++)
            {
                if (CardsList[i].cardVisual != null)
                    CardsList[i].cardVisual.UpdateIndex(transform.childCount);
            }
        }
    }
    private void BeginDrag(Card card)
    {
        selectedCard = card;

    }
    private void EndDrag(Card card)
    {
        if (selectedCard == null)
            return;

        selectedCard.transform.localPosition =
            selectedCard.IsSelected() ? new Vector3(0, selectedCard.SelectionOffset, 0) : Vector3.zero;

        rect.sizeDelta += Vector2.right;
        rect.sizeDelta -= Vector2.right;
        selectedCard = null;

    }

   

    private void CardPointerExit(Card card)
    {
        hoveredCard = null;


    }

    private void CardPointerEnter(Card card)
    {
        hoveredCard = card;

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(1))
        {
            foreach (Card card in CardsList)
            {
                card.Deselect();
            }
        }
        if (Input.GetKeyDown(KeyCode.Delete))
        {
            if (hoveredCard != null)
            {
                var card = hoveredCard;
                card.cardVisual.ParticleEffect.Play();
                card.cardVisual.DissloveEffect.Play(1, 0.1f, 0.4f, () =>
                {
                    card.cardVisual.ParticleEffect.Stop();
                    Destroy(card.transform.parent.gameObject);
                    CardsList.Remove(card);
                });
                

            }
            // if (selectedCard != null)
            // {
            //     var card = selectedCard;
            //     card.cardVisual.DissloveEffect.Play(1, 0, 0.5f, () =>
            //     {
            //         Destroy(card.transform.parent.gameObject);
            //         CardsList.Remove(card);
            //     });
            //     
            //
            // }
        }
        if (selectedCard == null)
            return;

        if (isCrossing)
            return;

        for (int i = 0; i < CardsList.Count; i++)
        {

            if (selectedCard.transform.position.x > CardsList[i].transform.position.x)
            {
                if (selectedCard.ParentIndex() < CardsList[i].ParentIndex())
                {
                    Swap(i);
                    break;
                }
            }

            if (selectedCard.transform.position.x < CardsList[i].transform.position.x)
            {
                if (selectedCard.ParentIndex() > CardsList[i].ParentIndex())
                {
                    Swap(i);
                    break;
                }
            }
        }
    
    }
    
    void Swap(int index)
    {
        isCrossing = true;

        Transform focusedParent = selectedCard.transform.parent;
        Transform crossedParent = CardsList[index].transform.parent;

        CardsList[index].transform.SetParent(focusedParent);
        CardsList[index].transform.localPosition = CardsList[index].IsSelected()
            ? new Vector3(0, CardsList[index].SelectionOffset, 0)
            : Vector3.zero;

        selectedCard.transform.SetParent(crossedParent);

        isCrossing = false;


        if (CardsList[index].cardVisual == null)
            return;

        bool swapIsRight = CardsList[index].ParentIndex() > selectedCard.ParentIndex();
        CardsList[index].cardVisual.Swap(swapIsRight ? -1 : 1);

        //Updated Visual Indexes
        foreach (Card card in CardsList)
        {
            card.cardVisual.UpdateIndex(transform.childCount);
        }
       
    }
}
